package com.haike.pushjobs.jobs;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpConfig;
import cn.hutool.extra.ftp.FtpMode;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.haike.pushjobs.config.GAOLANGANFtpConfig;
import com.haike.pushjobs.service.TPushRecordService;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.ibatis.session.SqlSession;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.*;
import java.util.regex.Pattern;


/**
 * 预报 - 海浪图片信息添加到数据库
 * 根据/www/gaolangan/web/Figure_wave/2025102312目录, 将文件信息添加到数据库
 */
@Slf4j
@DisallowConcurrentExecution
@Component
public class Download_t_yubao_wave_img_Job_from_ftp implements Job {

    @Autowired
    SqlSession daoSession;

    @Autowired
    TPushRecordService pushRecordService;

    @Autowired
    private GAOLANGANFtpConfig GAOLANGANFtpConfig;

    String description = "";

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        long funStartTime = System.currentTimeMillis();
        description = context.getJobDetail().getDescription();
        try {
            String param = context.getMergedJobDataMap().getString("param");
            log.info(description + "开始 - 参数: {}", param);

            Map<String, Object> paramMap = JSONUtil.toBean(param, Map.class);

            runTask(paramMap);

        } catch (Exception e) {
            log.error(description + "执行出错", e);
        } finally {
            log.info(description + "执行完成: {} 毫秒", System.currentTimeMillis() - funStartTime);
            log.info("[{}]清除数据源上下文", description);
            DynamicDataSourceContextHolder.clear();
        }
    }


    //region 执行任务

    String ftpRootDir = "/GFS+WRF+ADCIRC+SWAN/ADCIRC+SWAN_GFS/Figure_wave/";

    /**
     * 执行任务
     *
     * @param paramMap
     */
    public void runTask(Map<String, Object> paramMap) {
//        var img_dir = paramMap.get("img_dir").toString();
        List<Map<String, Object>> listResult = new ArrayList<>();

        // FTP服务器配置（使用提供的信息）
        String host = GAOLANGANFtpConfig.getHost();     // FTP服务器主机地址
        int port = GAOLANGANFtpConfig.getPort();        // 端口
        String username = GAOLANGANFtpConfig.getUsername(); // 用户名
        String password = GAOLANGANFtpConfig.getPassword(); // 密码
        // 创建FTP连接配置
        FtpConfig config = new FtpConfig(host, port, username, password, Charset.defaultCharset());
        // 建立FTP连接
        try (Ftp ftp = new Ftp(config, FtpMode.Passive)) {

            var dirList = ftp.lsFiles(ftpRootDir, file -> file.isDirectory());
            if (dirList.size() == 0) {
                log.info("无目录");
                return;
            }
            // dirList进行排序, 降序
            dirList.sort(Comparator.comparing(FTPFile::getName).reversed());

            try {
                for (int i = 0; i <= 1; i++) {
                    listResult.addAll(getPngFileDetails(ftp, dirList.get(i)));
                }

                System.out.println(listResult);
                for (Map<String, Object> item : listResult) {
                    item.put("id", IdUtil.getSnowflakeNextId());
                    daoSession.insert("data.insert_t_yubao_wave_img", item);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            log.error("FTP操作出错: " + e.getMessage(), e);
        }

    }
    //endregion

    /**
     * 获取指定目录下的PNG文件信息，提取时间并返回文件详情
     *
     * @param directoryPath 目录路径
     * @return 文件详情列表
     */
    public List<Map<String, Object>> getPngFileDetails(Ftp ftp, FTPFile directoryPath) {
        List<Map<String, Object>> fileDetails = new ArrayList<>();

        try {
            String rootDir = ftpRootDir + directoryPath.getName() + "/";
            var files = ftp.lsFiles(rootDir, file -> file.getName().endsWith(".png"));
//            var files = Files.list(directoryPath).collect(Collectors.toList());
//            files.sort(Comparator.comparing(Path::getFileName).reversed());
            if (files == null || files.size() == 0) {
                return fileDetails;
            }

            for (FTPFile file : files) {
                String fileName = file.getName();
                Map<String, Object> fileInfo = new HashMap<>();

                // SML_Wave_GLG_F202510272000.png, 使用正则提取出202510272000
                var matcher = Pattern.compile("SML_Wave_GLG_F(\\d+)\\.png").matcher(fileName);
                if (matcher.find()) {
                    var time = matcher.group(1);
                    var imgTime = DateUtil.parse(time, "yyyyMMddHHmm");
                    fileInfo.put("data_time", imgTime);
                }

                fileInfo.put("file_path", directoryPath.getName() + "/" + fileName);
                fileInfo.put("file_name", fileName);
//                fileInfo.put("size", Files.size(file));
//                fileInfo.put("lastModified", Files.getLastModifiedTime(file));
                fileDetails.add(fileInfo);
            }
        } catch (Exception e) {
            log.error("获取PNG文件详情失败: {}", e.getMessage(), e);
        }

        return fileDetails;
    }
}